#coding=utf-8
import logging
from flask import request

log = logging.getLogger(__name__)

def get_user_id():
    return request.identity["user"].user_id

def to_json(array, * args):
    json_list = []
    for i in array:
        json_list.append(i.to_json(*args))
    return json_list

def extract_inline_list(*keys, ** kw):
    ignore_keys = []
    item_dict = {}
    item_set_dict = {}
    for k, v in kw.iteritems():
        for prefix in keys:
            if k.startswith('%s-' % prefix):
                ignore_keys.append(k)
                if not (k.find('__') >= 0 or k.find('FORMS') >= 0):
                    ks = k.split('-')
                    if len(ks) == 2:
                        name = ks[1]
                        if not item_dict.has_key(prefix):
                            item_dict[prefix] = {}
                        item_dict[prefix][name] = v
                    elif len(ks) == 3:
                        index = ks[1]
                        name = ks[2]
                        if not item_set_dict.has_key(prefix):
                            item_set_dict[prefix] = {}
                        if not item_set_dict[prefix].has_key(index):
                            item_set_dict[prefix][index] = {}
                        item_set_dict[prefix][index][name] = v
    for i in ignore_keys:
        del kw[i]
    for k, v in item_dict.iteritems():
        kw[k] = v
    for k, v in item_set_dict.iteritems():
        kw[k] = []
        for i in list(set(map(int, v.keys()))):
            kw[k].append(v[str(i)])
    return kw

def getOr404(obj, id, redirect_url = "/index", message = "The record deosn't exist!"):
    try:
        v = DBSession.query(obj).get(id)
        if v : return v
        else : raise Exception("No such obj!")
    except Exception, e:
        log.exception(str(e))
        flash(message)
        redirect(redirect_url)
'''
def serveFile(filePath, fileName = None, contentType = "application/x-download", contentDisposition = "attachment"):
    response.headers['Content-type'] = 'application/x-download' if not contentType else contentType

    isIE = request.headers["User-Agent"].find("MSIE") > -1
    if not fileName:
        response.headers['Content-Disposition'] = "%s;filename=%s" % (contentDisposition, os.path.basename(filePath))
    else:
        if isIE :
            response.headers['Content-Disposition'] = "%s;filename=%s" % (contentDisposition, urllib.quote(fileName.encode('utf-8')))
        else:
            f = "=?utf-8?B?%s?=" % base64.b64encode(fileName)
            response.headers['Content-Disposition'] = "%s;filename=%s" % (contentDisposition, f)

    response.headers['Pragma'] = 'public' #for IE
    response.headers['Cache-control'] = 'max-age=0' #for IE
    f = open(filePath, 'rb')
    content = "".join(f.readlines())
    f.close()
    return content
'''